package com.xrz.service.impl;

import com.xrz.common.Result;
import com.xrz.dao.QaqUserDao;
import com.xrz.dao.UserInfoDao;
import com.xrz.pojo.QaqUser;
import com.xrz.pojo.UserInfo;
import com.xrz.service.OnlineUserStatsService;
import com.xrz.service.UserService;
import com.xrz.utils.XrzUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@Service
public class UserServiceImpl implements UserService {

    @Resource
    QaqUserDao qaqUserDao;
    @Resource
    UserInfoDao userInfoDao;
    @Resource
    private OnlineUserStatsService onlineUserStatsService;

    //手机号用户名注册
    @Override
    public Result registerPhone(QaqUser user) {

        if (user.getPhone()==null||user.getUsername() == null) {
            return Result.error(0, "手机号或账号不能为空！");
        }

        QaqUser qaqUser1 = qaqUserDao.selectByUsername(user.getUsername());
        if (qaqUser1 != null) {
            return Result.error(0, "账号已注册！");
        }
        QaqUser qaqUser = qaqUserDao.getUserByPhone(user.getPhone());
        if (qaqUser != null) {
            return Result.error(0, "手机号已注册！");
        }

        String uid = XrzUtils.getUuid();
        user.setUid(uid);
        UserInfo userInfo = new UserInfo();
        userInfo.setUid(uid);
        userInfo.setNickName(user.getUsername());
        userInfo.setPhone(user.getPhone());

        userInfoDao.insertSelective(userInfo);
        qaqUserDao.insertSelective(user);
        return Result.success("注册成功！");
    }

    //手机号或用户名登录
    @Override
    public Result loginPhone(QaqUser user) {



        if (user.getPhone() != null) {
            QaqUser qaqUser = qaqUserDao.getUserByPhoneAndUserName(user.getPhone());//根据手机号查出用户
            if (qaqUser == null) {
                return Result.error(0, "该用户未注册");
            }
            if (!user.getPassword().equals(qaqUser.getPassword())) {
                return Result.error(0, "账号或密码错误");
            }
            //记录用户数
            onlineUserStatsService.online(qaqUser.getId());
            UserInfo userInfo = userInfoDao.selectByUid(qaqUser.getUid());
            Map map=new HashMap<>();
            map.put("qaqUser",qaqUser);
            map.put("userInfo",userInfo);
            return Result.success(map);
        }

        return Result.error(0, "请输入手机号或账号");
    }
}